﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StockDetective
{
    public partial class Form2 : Form
    {

        //新建一个内部类用来储存文件路径和要加载到的DataGridView
        internal class infoObj
        {
            public string stockInfoPath;
            public DataGridView dataGridView;
        }


        public Form2()
        {
            InitializeComponent();
        }

        //在加载Form2的过程中将所有异常信息加载完成
        private void Form2_Load(object sender, EventArgs e)
        {
            Thread td1 = new Thread(new ParameterizedThreadStart(loadInfo));
            //Thread td2 = new Thread(new ParameterizedThreadStart(loadInfo));
            //Thread td3 = new Thread(new ParameterizedThreadStart(loadInfo));
            //Thread td4 = new Thread(new ParameterizedThreadStart(loadInfo));
            //Thread td5 = new Thread(new ParameterizedThreadStart(loadInfo));
            //Thread td6 = new Thread(new ParameterizedThreadStart(loadInfo));
            //Thread td7 = new Thread(new ParameterizedThreadStart(loadInfo));
            //Thread td8 = new Thread(new ParameterizedThreadStart(loadInfo));

            td1.Start(new infoObj { stockInfoPath = @"../../illStocks/error1.csv", dataGridView = dataGridView2 });
            //td2.Start(new infoObj { stockInfoPath = @"../../illStocks/error2.csv", dataGridView = dataGridView3 });
            //td3.Start(new infoObj { stockInfoPath = @"../../illStocks/error3.csv", dataGridView = dataGridView4 });
            //td4.Start(new infoObj { stockInfoPath = @"../../illStocks/error4.csv", dataGridView = dataGridView5 });
            //td5.Start(new infoObj { stockInfoPath = @"../../illStocks/error5.csv", dataGridView = dataGridView6 });
            //td6.Start(new infoObj { stockInfoPath = @"../../illStocks/error6.csv", dataGridView = dataGridView7 });
            //td7.Start(new infoObj { stockInfoPath = @"../../illStocks/error7.csv", dataGridView = dataGridView8 });
            //td8.Start(new infoObj { stockInfoPath = @"../../illStocks/error8.csv", dataGridView = dataGridView9 });

            loadDiscrip(1);
        }

        //在Form2关闭后再让Form1的按钮可以点击，防止出现多个Form2
        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            Form1 owner = (Form1)this.Owner;
            owner.buttonEnble();
        }

        //当通过选择不同的tabPage选择要查看的异常时，触发此方法
        private void TabControl1_SelectedIndexChanged(Object sender, EventArgs e)
        {
            loadDiscrip(this.tabControl1.SelectedIndex + 1);
        }


        //加载异常的相关数据到上方文本框
        private void loadDiscrip(int errorCode)
        {
            this.Invoke((EventHandler)delegate
            {
                this.richTextBox1.Text = "This is error " + errorCode;
            });
        }

        //加载异常股票相关信息到表格中
        private void loadInfo(object obj)
        {
            string path = ((infoObj)obj).stockInfoPath; //@"../../illStocks/error1.csv";
            DataGridView dgview = ((infoObj)obj).dataGridView;
            DataTable stockInfoTable = CSV.OpenCSV(path);
            IEnumerator rows = stockInfoTable.Rows.GetEnumerator();

            this.Invoke((EventHandler)delegate
            {
            while (rows.MoveNext())
            {
                DataRow row = (DataRow)rows.Current;
                string duringTime = calTime(row["startTime"].ToString(), row["endTime"].ToString());
                dgview.Rows.Add(new object[] {  row["stockCode"],
                                                row["stockName"],//row["stockName"],//抓取后替代此空值
                                                row["date"],
                                                duringTime,//记得字符串转换
                                                row["quantity"],
                                                row["times"]
                                             });
                }
            });
        }

        //抓取股票名称
        private string getName(string stockcode)
        {
            stockcode = stockcode.ToLower();
            string info = GetContent("http://hq.sinajs.cn/list=" + stockcode);
            info = info.Substring(info.IndexOf(stockcode + "=") + 9);
            return info.Substring(1, info.IndexOf(",")-1);
        }

        //网页源码抓取
        string GetContent(string url)
        {
            string html = "";
            // 发送查询请求
            WebRequest request = WebRequest.Create(url);
            WebResponse response = null;
            try
            {
                response = request.GetResponse();
                // 获得流
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                html = sr.ReadToEnd();
                response.Close();
            }
            catch (Exception ex)
            {
                // 本机没有联网
                if (ex.GetType().ToString().Equals("System.Net.WebException"))
                {
                    //MessageBox.Show("请检查你的计算机是否已连接上互联网。", "提示");
                }
            }
            return html;
        }

        //产生持续时间字符串
        private string calTime(string s1, string s2)
        {
            string time = s1.Substring(0, s1.Length == 6 ? 2 : 1) + ":"
                          + s1.Substring(s1.Length - 4, 2) + ":"
                          + s1.Substring(s1.Length - 2) + "--"
                          + s2.Substring(0, s2.Length == 6 ? 2 : 1) + ":"
                          + s2.Substring(s2.Length - 4, 2) + ":"
                          + s2.Substring(s2.Length - 2);
            return time;
        }

        private void DataGridViewSortCompare(object sender, DataGridViewSortCompareEventArgs e)
        {
            Regex strComp = new Regex(@"stockName\d+");
            Regex numCmp1 = new Regex(@"quantity");
            Regex numCmp2 = new Regex(@"times");

            if (strComp.Match(e.Column.Name).Success)
            {
                e.SortResult = string.Compare(Convert.ToString(e.CellValue1), Convert.ToString(e.CellValue2));
            }
            else if(numCmp1.Match(e.Column.Name).Success 
                    || numCmp2.Match(e.Column.Name).Success)
            {

                double num1 = Convert.ToDouble(e.CellValue1);
                double num2 = Convert.ToDouble(e.CellValue2);
                e.SortResult = num1 > num2 ? 1 : (num1 < num2 ? -1 : 0);
            }

            //这一步很关键，表此事件已处理完，无须再次处理
            e.Handled = true;
        }

        private void dataGridView2_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString()
            if (e.RowIndex.ToString().Equals("-1"))
                return;
            StockChart sc = new StockChart("20161010", dataGridView2.Rows[e.RowIndex].Cells[0].Value.ToString());
            sc.Show();
        }
    }
}
